package com.tuyan.aixiang.activity.web;

import android.content.Intent;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.smtt.sdk.WebView;
import com.tuyan.aixiang.activity.fullplayer.FullPlayerActivity;
import com.tuyan.aixiang.common.BaseActivity;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.common.M;
import com.tuyan.aixiang.common.StorageKey;
import com.tuyan.aixiang.model.YsDevice;
import com.tuyan.aixiang.util.StorageUtil;
import com.tuyan.aixiang.util.SystemUtil;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZOpenSDK;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//import com.tuyan.aixiang.activity.player.PlayerActivity;

public class JsBridge {

    private static final String TAG = "JsBridge";

    private WebView webview;

    private BaseActivity activity;


    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;

    private Boolean isFragment;

    public JsBridge(BaseActivity activity, WebView webView, Boolean isFragment) {
        this.activity = activity;
        this.webview = webView;
        this.isFragment = isFragment;
    }

    private void onInvoke(int resId, JsResult result) {
        String res = result.toString();
        String jsStr = "javascript:onInvoke(" + resId + ",'" + res + "')";
        activity.runOnUiThread(() -> {
            webview.loadUrl(jsStr);
        });
    }

    private JsonObject getJsonObject(String json) {
        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
        return jsonObject;
    }

    @JavascriptInterface
    public void closeWeb(final String json) {
        if(isFragment) return;
        activity.runOnUiThread(activity::finish);
    }

    @JavascriptInterface
    public void closeWindow(final String json) {
        this.closeWeb(json);
    }

    @JavascriptInterface
    public void openWebview(final String json) {
        int resId = getJsonObject(json).get("resId").getAsInt();
        String url = getJsonObject(json).get("url").getAsString();
        onInvoke(resId, new JsResult());
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url", url);
        activity.startActivity(intent);
    }

    @JavascriptInterface
    public void getVersionCode(final String json) {
        try {
            JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
            int resId = jsonObj.get("resId").getAsInt();
            String versionName = SystemUtil.getVersionName(activity);
            resultSuccess(resId, versionName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void closeAndBackToHome(final String json) {
        activity.runOnUiThread(() -> {
            StorageUtil.setBoolean(StorageKey.CLOSE_BACK, true);
            activity.finish();
        });
    }


    private int locationId = 0;

    @JavascriptInterface
    public void getLocation(final String json) {
        locationId = getJsonObject(json).get("resId").getAsInt();
        gdLocate();
    }

    /**
     * 高德定位
     */
    private void gdLocate() {
        activity.withLocationPermission(() -> {

            AMapLocationListener mLocationListener = aMapLocation -> {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        //
                        Log.d(TAG, aMapLocation.getLatitude() + "-" + aMapLocation.getLongitude());
                        resultSuccess(locationId, M.m().put("address", aMapLocation.getAddress()).put("aoiName", aMapLocation.getAoiName()).put("latitude", aMapLocation.getLatitude()).put("longitude", aMapLocation.getLongitude()));
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.d(TAG, aMapLocation.getErrorCode() + aMapLocation.getErrorInfo());
                        resultFailed(locationId);
                    }
                }
            };
            if (null == mLocationClient) {
                //初始化定位
                mLocationClient = new AMapLocationClient(activity);
                //设置定位回调监听
                mLocationClient.setLocationListener(mLocationListener);
                //初始化AMapLocationClientOption对象
                AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
                //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //获取一次定位结果：
                //该方法默认为false。
                mLocationOption.setOnceLocation(true);

                mLocationOption.setNeedAddress(true);
                //获取最近3s内精度最高的一次定位结果：
                //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)
                // 接口也会被设置为true，反之不会，默认为false。
                mLocationOption.setOnceLocationLatest(true);

                //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
                mLocationOption.setHttpTimeOut(20000);
                //关闭缓存机制
                mLocationOption.setLocationCacheEnable(false);
                //给定位客户端对象设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
            }

            //启动定位
            mLocationClient.startLocation();
        });
    }


    // 报警 1
    // 消息 2
//    公告 3
//    共享 4

    @JavascriptInterface
    public void updateShortcut(final String json) {
        int resId = getJsonObject(json).get("resId").getAsInt();
        JsonArray jsonArray = getJsonObject(json).get("data").getAsJsonArray();
        StorageUtil.setObject(StorageKey.SHORT_CUT, jsonArray);
        onInvoke(resId, new JsResult());
    }

    @JavascriptInterface
    public void getShortcut(final String json) {
        int resId = getJsonObject(json).get("resId").getAsInt();
        JsonArray jsonArray = StorageUtil.getObject(StorageKey.SHORT_CUT, JsonArray.class);
        if (null == jsonArray) {
            jsonArray = new JsonArray();
        }
        resultSuccess(resId, jsonArray);
    }


    @JavascriptInterface
    public void getCapture(final String json) {

        int resId = getJsonObject(json).get("resId").getAsInt();
        String serial = getJsonObject(json).get("deviceSerial").getAsString();
        int channelNo = getJsonObject(json).get("channelNum").getAsInt();
        JsResult result = new JsResult();

        Observable.create((Observable.OnSubscribe<String>) subscriber -> {
            try {
                String url = EZOpenSDK.getInstance().captureCamera(serial, channelNo);
                subscriber.onNext(url);
            } catch (BaseException e) {
                e.printStackTrace();
                subscriber.onNext(null);
            } finally {
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String s) {
                        resultSuccess(resId, s);
                    }
                });

    }

    @JavascriptInterface
    public void openVidPlayer(final String json) {
        YsDevice device = new Gson().fromJson(json, YsDevice.class);
        FullPlayerActivity.startPlayActivity(activity, device);
    }

    @JavascriptInterface
    public void setNoticeSound(final String json) {
        int resId = getJsonObject(json).get("resId").getAsInt();
        int soundType = getJsonObject(json).get("type").getAsInt();
        StorageUtil.setInt(StorageKey.NOTICE_SOUND, soundType);
        resultSuccess(resId, true);
    }

    @JavascriptInterface
    public void getNoticeSound(final String json) {
        int resId = getJsonObject(json).get("resId").getAsInt();
        int soundType = StorageUtil.getInt(StorageKey.NOTICE_SOUND, Constant.NOTICE_SOUND_TYPE_DEFAULT);
        resultSuccess(resId, soundType);
    }


    private <T> void resultSuccess(Integer resId, T data) {
        JsResult<T> result = new JsResult<>();
        result.setCode(0);
        result.setData(data);
        onInvoke(resId, result);

    }

    private void resultFailed(Integer resId) {
        JsResult result = new JsResult();
        result.setCode(-1);
        onInvoke(resId, result);
    }

}
